package com.yulang.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yulang.web.mapper.SysUserMapper;
import com.yulang.web.pojo.SysUser;
import com.yulang.web.pojo.SysUserRole;
import com.yulang.web.service.SysUserRoleService;
import com.yulang.web.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private static final String INIT_PASSWORD = "$2a$10$rDkPvvAFV8kqwvKJzwlRv.i.q.wz1w1pz0SFsHn/55jNeZFQv/eCm";

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public SysUser findByUsername(String username) {
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda().eq(SysUser::getUsername,username);
        return this.getOne(query);
    }

    @Override
    public SysUser findByPhone(String mobile) {
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda().eq(SysUser::getMobile,mobile);
        return this.getOne(query);
    }

    @Transactional
    @Override
    public void saveOrUpdates(SysUser sysUser) {
        if(sysUser.getId()==null){
            sysUser.setPassword(INIT_PASSWORD);
        }
        this.saveOrUpdate(sysUser);
        QueryWrapper<SysUserRole> query = new QueryWrapper<>();
        query.lambda().eq(SysUserRole::getUserId,sysUser.getId());
        sysUserRoleService.remove(query);
        sysUser.getRoleIds().forEach(item->{
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(item);
            userRole.setUserId(sysUser.getId());
            sysUserRoleService.save(userRole);
        });
    }

    @Override
    public void delete(Long id) {
        UpdateWrapper<SysUser> remove = new UpdateWrapper<>();
        remove.set("is_enabled",false);
        remove.lambda().eq(SysUser::getId,id);
        this.update(remove);
    }
}
